<template>
  <div v-if="columns.length" class="card table-search">
    <el-form ref="formRef" :model="searchParam">
      <grid ref="gridRef" :collapsed="collapsed" :cols="searchCol" :gap="[20, 0]">
        <grid-item v-for="(item, index) in columns" :key="item.prop" v-bind="getResponsive(item)" :index="index">
          <el-form-item :label="`${item.search?.label || item.label} :`">
            <div style="display: flex; align-items: center">
              <search-form-item :column="item" :search-param="searchParam" />
              <!-- start -->
              <div v-if="item.search?.props?.type === 'datetimerange'" style="margin-top: 8px; margin-left: 10px">
                <el-dropdown @command="changeCommand">
                  <el-button size="small" type="primary">
                    快捷
                    <el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item v-for="ele in commandList" :key="ele.key" :command="ele.key">{{ ele.name }}</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <!-- end -->
            </div>
          </el-form-item>
        </grid-item>
        <grid-item suffix>
          <div class="operation">
            <el-button :icon="Search" type="primary" @click="search">搜索</el-button>
            <el-button :icon="Delete" @click="reset">重置</el-button>
            <el-button v-if="showCollapse" class="search-isOpen" link type="primary" @click="collapsed = !collapsed">
              {{ collapsed ? '展开' : '合并' }}
              <el-icon class="el-icon--right">
                <component :is="collapsed ? ArrowDown : ArrowUp" />
              </el-icon>
            </el-button>
          </div>
        </grid-item>
      </grid>
    </el-form>
  </div>
</template>
<script setup lang="ts" name="SearchForm">
import { ArrowDown, ArrowUp, Delete, Search } from '@element-plus/icons-vue'
import { computed, ref, toRefs } from 'vue'
import SearchFormItem from './components/SearchFormItem.vue'
import {
  getDaysInCurrentMonth,
  getDaysInLastMonth,
  getDaysInLastYear,
  getDaysSinceSeasonStart,
  getDaysSinceStartOfYear,
  getLastQuarterDays,
  weekDay,
} from '/@/utils/date'
import { formatDate } from '/@/utils/date-formatter'
import { commandList } from '/@/utils/serviceDict'
import GridItem from '/@vab/components/Grid/components/GridItem.vue'
import Grid from '/@vab/components/Grid/index.vue'
import { BreakPoint } from '/@vab/components/Grid/interface'
import { ColumnProps } from '/@vab/components/ProTable/interface'

interface ProTableProps {
  columns?: ColumnProps[] // 搜索配置列
  searchParam?: { [key: string]: any } // 搜索参数
  searchCol: number | Record<BreakPoint, number>
  search: (params: any) => void // 搜索方法
  reset: (params: any) => void // 重置方法
}

// 默认值
const props = withDefaults(defineProps<ProTableProps>(), {
  columns: () => [],
  searchParam: () => ({}),
})

const param = toRefs(props)

// 获取响应式设置
const getResponsive = (item: ColumnProps) => {
  return {
    span: item.search?.span,
    offset: item.search?.offset ?? 0,
    xs: item.search?.xs,
    sm: item.search?.sm,
    md: item.search?.md,
    lg: item.search?.lg,
    xl: item.search?.xl,
  }
}

// 是否默认折叠搜索项
const collapsed = ref(true)

// 获取响应式断点
const gridRef = ref()
const breakPoint = computed<BreakPoint>(() => gridRef.value?.breakPoint)

// 判断是否显示 展开/合并 按钮
const showCollapse = computed(() => {
  let show = false
  props.columns.reduce((prev, current) => {
    prev +=
      (current.search![breakPoint.value]?.span ?? current.search?.span ?? 1) +
      (current.search![breakPoint.value]?.offset ?? current.search?.offset ?? 0)
    if (typeof props.searchCol !== 'number') {
      if (prev >= props.searchCol[breakPoint.value]) show = true
    } else {
      if (prev >= props.searchCol) show = true
    }
    return prev
  }, 0)
  return show
})

interface Emits {
  (name: 'changeDate', value: { time: string[]; key: {} }): void
}
const emits = defineEmits<Emits>()
// 修改列表
const changeCommand = (e: number) => {
  let time = ['2024-11-05 00:00', '2024-12-10 00:00']
  let start = 0 // 可变日期 （前面）
  let end = 0 // 当天日期（后面）

  switch (e) {
    case 1:
      // 今天
      start = 0
      break
    case 2:
      // 本周
      start = -weekDay() + 1
      break
    case 3:
      // 本月
      start = -getDaysInCurrentMonth() + 1
      break
    case 4:
      // 本季度
      start = -getDaysSinceSeasonStart() + 1
      break
    case 5:
      // 本年
      start = -getDaysSinceStartOfYear()
      console.log(getDaysSinceStartOfYear())
      break
    case 6:
      // 昨天
      start = -1
      break
    case 7:
      // 上周
      start = -(7 + weekDay()) + 1
      end = -weekDay()
      break
    case 8:
      // 上月
      start = -(getDaysInCurrentMonth() + 1 + getDaysInLastMonth()) + 1
      end = -getDaysInCurrentMonth()
      break
    case 9:
      // 上季度
      start = -(getDaysSinceSeasonStart() + 1 + getLastQuarterDays()) + 1
      end = -getDaysSinceSeasonStart()
      break
    case 10:
      // 上年
      start = -(getDaysSinceStartOfYear() + 1 + getDaysInLastYear()) + 1
      end = -getDaysSinceStartOfYear() - 1
      break
  }
  time = [formatDate(start, 'start', 'yyyy-MM-dd') + ' 00:00', formatDate(end, 'start', 'yyyy-MM-dd') + ' 00:00']

  emits('changeDate', { time, key: props.searchParam })
}
</script>
